package com.systemsjr.mpf.account;

import java.text.SimpleDateFormat;
import java.util.Date;

import android.app.Activity;
import android.app.ListActivity;
import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;

import com.systemsjr.mpf.MpfActivity;
import com.systemsjr.mpf.R;
import com.systemsjr.mpf.db.ExpenseTypeContentProvider;
import com.systemsjr.mpf.expense.ExpenseType;

public class ViewAccountInstanceActivity extends ListActivity {

	private InstanceListAdapter adapter;
	private ListView listView;
	private Cursor c;
	private AccountInstance instance;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_view_account_instance);

		Bundle bundle = getIntent().getExtras();
		final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		
		TextView description = (TextView) findViewById(R.id.descriptionText);
		TextView budget = (TextView) findViewById(R.id.budgetText);
		TextView spent = (TextView) findViewById(R.id.spentText);
		final TextView endDate = (TextView) findViewById(R.id.endDateText);
		TextView startDate = (TextView) findViewById(R.id.startDateText);

		/**
		 * The Master of the screen
		 */
		if (bundle != null && bundle.size() > 0) {

			if (bundle.get(AccountInstance.TABLE_NAME) != null) {
				
				instance = (AccountInstance) bundle
						.get(AccountInstance.TABLE_NAME);
				
				LinearLayout spentLayout = (LinearLayout) findViewById(R.id.spentLayout);
				if (instance.getBudget() > instance.getSpent()) {
					spentLayout.setBackgroundColor(getResources().getColor(
							R.color.budget_color_green));
				} else {
					spentLayout.setBackgroundColor(getResources().getColor(
							R.color.budget_color_red));
				}

				description.setText(instance.getInstance());
				budget.setText("Budget: " + instance.getBudget());
				spent.setText("Spent: " + instance.getSpent());

				if (instance.getCloseDate() != null) {
					endDate.setText(" to "
							+ sdf.format(instance.getCloseDate()));
				}
				startDate.setText(sdf.format(instance.getStartDate()));

				/**
				 * Start of the details
				 */
				String[] from = { ExpenseType.EXPENSE_TYPE, ExpenseType.SPENT };
				int[] to = { R.id.instanceExpense, R.id.instanceExpenseSpent };
				String selection = "_id IN (SELECT EXPENSE_TYPE_FK FROM EXPENSE WHERE ACCOUNT_INSTANCE_FK = ?)";
				String[] selectionArgs = { "" + instance.getId() };

				ExpenseTypeContentProvider.addSpent(instance.getId());

				c = getContentResolver().query(ExpenseType.CONTENT_URI,
						ExpenseType.getNewProjections(), selection,
						selectionArgs, "EXPENSE_TYPE ASC");

				startManagingCursor(c);

				adapter = new InstanceListAdapter(this,
						R.layout.view_instance_list_entry, c, from, to);

				listView = getListView();
				listView.setAdapter(adapter);

				ExpenseTypeContentProvider.removeSpent();
			}

			Button closeButton = (Button) findViewById(R.id.closeInstanceButton);

			if (instance.getCloseDate() != null) {
				closeButton.setVisibility(Button.INVISIBLE);
			} else {
				closeButton.setVisibility(Button.VISIBLE);
			}

			closeButton.setOnClickListener(new OnClickListener() {

				/**
				 * Only bother with updating the close date
				 */
				@Override
				public void onClick(View v) {

					instance.setCloseDate(new Date());
					String closeD = sdf.format(new Date());
					ContentValues values = new ContentValues();
					values.put(AccountInstance.CLOSE_DATE,
							 closeD);
					
					getContentResolver()
							.update(AccountInstance.CONTENT_URI,
									values,
									AccountInstance.ID + " = "
											+ instance.getId(), null);
					endDate.setText(" to " + closeD);
				}
			});
		}
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.view_account_instance, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// Handle action bar item clicks here. The action bar will
		// automatically handle clicks on the Home/Up button, so long
		// as you specify a parent activity in AndroidManifest.xml.
		int id = item.getItemId();
		if (id == R.id.action_settings) {
			return true;
		}
		return super.onOptionsItemSelected(item);
	}

	@Override
	protected void onResume() {
		super.onResume();
		// c.requery();
		adapter.notifyDataSetChanged();
		listView.invalidateViews();
	}

	@Override
	protected void onListItemClick(ListView l, View v, int position, long id) {
		super.onListItemClick(l, v, position, id);
		Intent intent = new Intent(ViewAccountInstanceActivity.this,
				ViewInstanceExpenseByType.class);

		if (adapter != null) {
			Cursor c = (Cursor) adapter.getItem(position);
			ExpenseType type = new ExpenseType();

			type.setId(c.getLong(c.getColumnIndex(ExpenseType.ID)));
			type.setCode(c.getString(c.getColumnIndex(ExpenseType.CODE)));
			type.setExpenseType(c.getString(c
					.getColumnIndex(ExpenseType.EXPENSE_TYPE)));
			type.setSpent(c.getDouble(c.getColumnIndex(ExpenseType.SPENT)));

			intent.putExtra(ExpenseType.TABLE_NAME, type);
			intent.putExtra(AccountInstance.TABLE_NAME, instance);
		}

		startActivityForResult(intent, 1);
	}
}
